'use strict';

const {
	XMLParser
} = require("fast-xml-parser");
const {
	mainSpaceId
} = require('config-main-space')
const db = uniCloud.database();
exports.main = async (event, context) => {
	let response = {
		mpserverscssComposedResponse: true,
		statusCode: 200
	};
	let data = event.body;
	if (event.isBase64Encoded) {
		data = new Buffer(data, 'base64').toString();
	}

	let res = {};
	let payObj = {};

	const path = event.path;
	switch (path) {
		case '/alipay':

			payObj.name = '支付宝支付';
			payObj.way = 'alipay';

			let queryArr = data.split("&");
			queryArr.forEach(function(item) {
				let key = item.split("=")[0];
				res[key] = item.split("=")[1];
			});
			res.total_fee = res.total_amount * 100;
			res.transaction_id = res.trade_no;

			break;
		case '/wechat':

			payObj.name = '微信支付';
			payObj.way = 'wechat';

			const parser = new XMLParser();
			res = parser.parse(data);
			res = res.xml;

			try {
				//特殊处理transaction_id
				let transaction_ids = data.split('<transaction_id><![CDATA[');
				if (transaction_ids.length > 0) {
					res.transaction_id = transaction_ids[1].split("]]></transaction_id>")[0];
				}
			} catch (e) {
				uniCloud.logger.info("微信支付支付通知异常: ", JSON.stringify(e));
			}

			break;
		default:

			uniCloud.logger.info(`支付通知标识不正确`);
			return response;
	}
	if (res && ((res.return_code && 'SUCCESS' === res.return_code) || (res.trade_status && 'TRADE_SUCCESS' ===
			res.trade_status))) {
		let outTradeNo = res.out_trade_no ? res.out_trade_no : null;
		let transactionId = res.transaction_id ? res.transaction_id : null;
		let alipayVouchers = res.alipay_vouchers ? res.alipay_vouchers : null;

		if (!outTradeNo) {
			uniCloud.logger.info(`outTradeNo参数丢失`);
			return response;
		}
		let balanceOrder = await db.collection('wmz-entitlement-balance-order').doc(outTradeNo).get()
		balanceOrder = balanceOrder.data[0]
		if (balanceOrder) {
			if (balanceOrder.status === '待付款') {
				await db.collection('wmz-entitlement-balance-order').doc(outTradeNo).update({
					status: '已付款',
					pay_time: new Date().getTime(),
					trade_no: transactionId
				})
				let appletInfoData = await db.collection('wmz-applet-info').doc(balanceOrder.app_id).get()
				appletInfoData = appletInfoData.data[0]
				let balance = balanceOrder.money * 1
				if (appletInfoData.balance) {
					balance += appletInfoData.balance * 1
				}
				await db.collection('wmz-applet-info').doc(balanceOrder.app_id).update({
					balance: balance
				})
				await db.collection('wmz-entitlement-balance').add({
					app_id: balanceOrder.app_id,
					shop_id: balanceOrder.app_id,
					create_time: new Date().getTime(),
					money: balanceOrder.money * 1,
					name: "余额充值",
					type: "收入",
					way: "余额充值",
					trade_no: transactionId
				})
			}
		}
	}
}